# coding:utf-8

import warnings

warnings.simplefilter('ignore', DeprecationWarning)
import pymysql
from utils.common.log import Log
import logging
from config.confManage import db_manage

Log()


class MYSQL(object):

    def __init__(self):
        self.host = db_manage("${host}$")
        self.user = db_manage("${user}$")
        self.password = db_manage("${password}$")
        self.database = db_manage("${database}$")
        self.charset = db_manage("${charset}$")
        self.port = int(db_manage("${port}$"))
        try:
            logging.debug("正在连接数据库..")
            self.conn = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database,
                                        port=self.port, charset=self.charset)
        except Exception as e:
            raise e

    def connect_database(self):
        """
        连接数据库
        :return:
        """
        try:

            # 查看连接是否成功
            cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
            logging.debug("数据库连接成功..")
            return cursor
        except Exception as e:
            logging.error("连接数据库失败..{}".format(e))
            raise e

    def run_sql(self, sql):
        """
        执行sql语句
        :param sql:
        :return:
        """
        try:
            logging.debug("准备执行SQL语句..")
            cursor = self.connect_database()
            cursor.execute(sql)
            rs = cursor.fetchall()
            return rs
        except Exception as e:
            logging.error("执行SQL失败..{}".format(e))
            raise

    def commit(self):
        self.conn.commit()


if __name__ == "__main__":
    DB = MYSQL()
    datas = DB.run_sql("select * from smoker where device_status = 1 ")

    print(datas)
